package mygameclient;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GamePanel extends JPanel {
    static CellPanel[][] cells = new CellPanel[3][3];
    private static final String CROSS_IMAGE = "E:/cross/cross.jpg";
    private static final String NULL_IMAGE = "E:/cross/null.jpg";
    static int cellType;                                  // 0 = null , 1 = cross , -1 = empty
    static int gameIndex;
    static boolean start = false;
    static int thisPlayerCode;

    public int getThisPlayerCode() {
        return thisPlayerCode;
    }

    public void setThisPlayerCode(int thisPlayerCode) {
        this.thisPlayerCode = thisPlayerCode;
    }

    public GamePanel() {
        setBackground(Color.WHITE);
        setPreferredSize(new Dimension(360, 360));
        setLayout(new GridLayout(3, 3));

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                CellPanel cell = new CellPanel();
                add(cell);
                cell.setVisible(true);
                cell.addMouseListener(new MouseHandler());
                cells[i][j] = cell;
            }
        }
    }

    public void paintCell(CellPanel currentCell, int cellType) {
        String cellPict = (cellType == 0) ? NULL_IMAGE : CROSS_IMAGE;
        try {
            BufferedImage img;
            img = ImageIO.read(new File(cellPict));
            currentCell.setImage(img);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void erasePanel(){
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                cells[i][j].clearImage();
            }
        }
    }

    class MouseHandler extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent event) {
            CellPanel currentCell = (CellPanel) event.getSource();
            if (start && currentCell.isEditable()) {
                paintCell(currentCell, cellType);
                currentCell.setEditable(false);

                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        if (currentCell == cells[i][j]) {
                            ClientCommands.setCell(i, j, cellType ,gameIndex);
                            start = false;
                        }
                    }
                }
            }
        }
    }
}
